const constant = require('./constant');

/**
 * 调用普通接口
 * @param {*} url 
 * @param {*} method 
 * @param {*} data 
 * @param {*} header 
 */
function fun(url, method, data, header) {
  data = data || {};
  header = header || {
    'content-type': 'application/json'
  };
  // let sessionId = wx.getStorageSync("UserSessionId");
  // if (sessionId) {
  //   if (!header || !header["SESSIONID"]) {
  //     header["SESSIONID"] = sessionId;
  //   }
  // }
  // wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    // 正常调用接口
    wx.request({
      url: url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        // 如果未经授权或token过期，需要重新授权，跳转回/pages/index/index页面
        if (res.data.success == false && res.data.code == constant.httpStatus.unauthorized) {
          console.warn('未经授权或token过期，需要重新授权');
          wx.reLaunch({
            url: "/pages/index/index?authViewShow=true"
          });
          reject(res);
        }

        // 如果已授权并且token没有过期，则正常执行
        resolve(res);
      }
    });
  });

  promise.action = async function(func){
    // 接收action的返回值，如果没有返回值则为undefined
    let actionValue = await promise.then(func);
    if (url.includes(constant.api.service.url.auth)) {
      // 如果是调用登录接口，则添加登录日志
      let user = wx.getStorageSync('user');
      let data = {
        userId: user.userId,
      };
      saveLoginLog(data);
    } else {
      // 如果是其他返回数据的接口，则添加接口调用日志
      let user = wx.getStorageSync('user');
      let param = {
        userId: user.userId,
        // 用于解决接口格式为/api/diagnose/{codeOrName}的情况
        url: (actionValue && actionValue.url) ? actionValue.url : url,
        header: header,
        data: data,
        method: method,
      };
      saveApiCallLog(param);
    }
    return promise;
  };

  return promise;
}

/**
 * 调用上传文件的接口
 * @param {*} url 
 * @param {*} name 
 * @param {*} filePath 
 */
function upload(url, name, filePath) {
  let header = {};
  // wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    // 正常调用接口
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res);
      }
    });
  });

  promise.then((result) => {
    // 添加接口调用日志
    saveApiCallLog(data);
  });

  return promise;
}

/**
 * 添加登录日志
 */
function saveLoginLog(data) {
  wx.request({
    url: constant.api.service.prefix + constant.api.service.url.saveLoginLog,
    header: {
      'content-type': 'application/json'
    }, // 还没有决定header里要不要加user
    data: data,
    method: 'post',
    success: function (res) {}
  });
}

/**
 * 添加接口调用日志
 */
function saveApiCallLog(data) {
  wx.request({
    url: constant.api.service.prefix + constant.api.service.url.saveApiCallLog,
    header: {
      'content-type': 'application/json'
    }, // 还没有决定header里要不要加user
    data: data,
    method: 'post',
    success: function (res) {}
  });
}

module.exports = {
  get: function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  post: function (url, data, header) {
    return fun(url, "POST", data, header);
  },
  upload: function (url, name, filePath) {
    return upload(url, name, filePath);
  }
};